<template>
  <div class="admin-students p-6" style="background-color: #FAF9F5;">
    <!-- 页面头部 -->
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">学生管理</h1>
        <p class="text-gray-600 mt-1">管理学生信息，包括查看、编辑、删除等操作</p>
      </div>
      <div class="flex items-center space-x-3">
        <button
          @click="showImportModal = true"
          class="inline-flex items-center justify-center rounded-[0.6rem] px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 text-gray-700 hover:border-gray-400 hover:bg-gray-50 focus:ring-gray-500 active:scale-[0.985]"
          style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
        >
          <i class="icon-[heroicons--arrow-up-tray] w-4 h-4 mr-2"></i>
          批量导入
        </button>
        <button
          @click="showAddModal = true"
          class="inline-flex items-center justify-center rounded-[0.6rem] px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed text-white border border-gray-300 hover:border-gray-400 focus:ring-blue-500 active:scale-[0.985]"
          style="background-color: #3B82F6; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);"
        >
          <i class="icon-[heroicons--plus] w-4 h-4 mr-2"></i>
          添加学生
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="rounded-[0.6rem] p-6 border border-gray-200 mb-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <!-- 搜索框 -->
        <div class="md:col-span-2">
          <label class="block text-sm font-medium text-gray-700 mb-2">搜索学生</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="icon-[heroicons--magnifying-glass] w-5 h-5 text-gray-400"></i>
            </div>
            <input
              v-model="searchQuery"
              type="text"
              class="block w-full rounded-[0.6rem] border border-gray-300 px-3 py-2 text-sm placeholder-gray-400 transition-all duration-200 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 pl-10"
              style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
              placeholder="输入姓名、学号、手机号或身份证号"
              @input="handleSearch"
            >
          </div>
        </div>
        
        <!-- 专业筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">专业筛选</label>
          <select
            v-model="selectedMajor"
            class="block w-full rounded-[0.6rem] border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
            @change="handleFilter"
          >
            <option value="">全部专业</option>
            <option v-for="major in majors" :key="major.id" :value="major.id">
              {{ major.name }}
            </option>
          </select>
        </div>
        
        <!-- 状态筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">报到状态</label>
          <select
            v-model="selectedStatus"
            class="block w-full rounded-[0.6rem] border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
            @change="handleFilter"
          >
            <option value="">全部状态</option>
            <option value="registered">已报到</option>
            <option value="not-registered">未报到</option>
          </select>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-200">
        <div class="flex items-center space-x-4">
          <span class="text-sm text-gray-600">
            已选择 {{ selectedStudents.length }} 个学生
          </span>
          <button
            v-if="selectedStudents.length > 0"
            @click="handleBatchDelete"
            class="text-sm text-red-600 hover:text-red-700"
          >
            批量删除
          </button>
        </div>
        
        <div class="flex items-center space-x-2">
          <button
            @click="exportStudents"
            class="inline-flex items-center justify-center rounded-[0.6rem] px-3 py-1.5 text-xs font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 text-gray-700 hover:border-gray-400 hover:bg-gray-50 focus:ring-gray-500 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <i class="icon-[heroicons--arrow-down-tray] w-3 h-3 mr-1"></i>
            导出
          </button>
          <button
            @click="refreshData"
            class="inline-flex items-center justify-center rounded-[0.6rem] px-3 py-1.5 text-xs font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 text-gray-700 hover:border-gray-400 hover:bg-gray-50 focus:ring-gray-500 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <i class="icon-[heroicons--arrow-path] w-3 h-3 mr-1"></i>
            刷新
          </button>
        </div>
      </div>
    </div>

    <!-- 学生列表 -->
    <div class="rounded-[0.6rem] border border-gray-200 overflow-hidden" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <h3 class="text-lg font-semibold text-gray-900">学生列表</h3>
        <p class="text-sm text-gray-600 mt-1">共 {{ filteredStudents.length }} 名学生</p>
      </div>
      <DataTable
        :data="filteredStudents"
        :columns="tableColumns"
        :loading="loading"
        :selectable="true"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @page-change="handlePageChange"
      >
        <!-- 头像列 -->
        <template #avatar="{ row }">
          <div class="flex items-center justify-center">
            <!-- 如果有有效的头像URL则显示头像图片 -->
            <img 
              v-if="isValidPhotoUrl(row.photo)" 
              :src="row.photo" 
              :alt="row.name"
              class="w-10 h-10 rounded-full object-cover border-2 border-gray-200"
              @error="handleImageError"
            />
            <!-- 否则显示默认样式（姓名首字母） -->
            <div 
              v-else
              class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-400 to-blue-600 flex items-center justify-center text-white font-medium text-sm"
            >
              {{ row.name ? row.name.charAt(0) : 'N' }}
            </div>
          </div>
        </template>
        
        <!-- 报到状态列 -->
        <template #registrationStatus="{ value }">
          <span :class="[
            'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
            value === 'registered' ? 'bg-green-100 text-green-800' :
            value === 'not-registered' ? 'bg-yellow-100 text-yellow-800' :
            'bg-gray-100 text-gray-800'
          ]">
            {{ getRegistrationStatusText(value) }}
          </span>
        </template>
        
        <!-- 缴费状态列 -->
        <template #paymentStatus="{ value }">
          <span :class="[
            'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
            value === 'paid' ? 'bg-green-100 text-green-800' :
            value === 'unpaid' ? 'bg-red-100 text-red-800' :
            value === 'partial' ? 'bg-yellow-100 text-yellow-800' :
            'bg-gray-100 text-gray-800'
          ]">
            {{ getPaymentStatusText(value) }}
          </span>
        </template>
        
        <!-- 操作列 -->
        <template #actions="{ row }">
          <div class="flex items-center justify-center space-x-3">
            <button
              @click="editStudent(row)"
              class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 hover:text-blue-700 transition-colors duration-200"
              title="编辑学生信息"
            >
              <i class="icon-[heroicons--pencil] w-4 h-4"></i>
            </button>
            <button
              @click="deleteStudent(row)"
              class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-red-50 text-red-600 hover:bg-red-100 hover:text-red-700 transition-colors duration-200"
              title="删除学生"
            >
              <i class="icon-[heroicons--trash] w-4 h-4"></i>
            </button>
          </div>
        </template>
      </DataTable>
    </div>

    <!-- 添加/编辑学生弹窗 -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-6">
          <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-semibold text-gray-900">
              {{ showAddModal ? '添加学生' : '编辑学生' }}
            </h3>
            <button
              @click="closeModal"
              class="text-gray-400 hover:text-gray-600"
            >
              <i class="icon-[heroicons--x-mark] w-6 h-6"></i>
            </button>
          </div>
          
          <form @submit.prevent="saveStudent" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- 基本信息 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">姓名 *</label>
                <input
                  v-model="studentForm.name"
                  type="text"
                  required
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入学生姓名"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">学号 *</label>
                <input
                  v-model="studentForm.studentId"
                  type="text"
                  required
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入学号"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">性别 *</label>
                <select
                  v-model="studentForm.sex"
                  required
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">请选择性别</option>
                  <option value="0">男</option>
                  <option value="1">女</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">身份证号 *</label>
                <input
                  v-model="studentForm.idCard"
                  type="text"
                  required
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入身份证号"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">手机号 *</label>
                <input
                  v-model="studentForm.contactPhone"
                  type="tel"
                  required
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入手机号"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">专业 *</label>
                <select
                  v-model="studentForm.majorId"
                  required
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">请选择专业</option>
                  <option v-for="major in majors" :key="major.id" :value="major.id">
                    {{ major.name }}
                  </option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">班级</label>
                <input
                  v-model="studentForm.className"
                  type="text"
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入班级"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">缴费状态</label>
                <select
                  v-model="studentForm.paymentStatus"
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="0">未缴费</option>
                  <option value="1">已缴费</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">报到状态</label>
                <select
                  v-model="studentForm.status"
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="0">未报到</option>
                  <option value="1">已报到</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">入住地点</label>
                <input
                  v-model="studentForm.dormBuilding"
                  type="text"
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入入住地点"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">寝室号</label>
                <input
                  v-model="studentForm.roomNumber"
                  type="text"
                  class="block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入寝室号"
                >
              </div>
            </div>
            
            <div class="flex items-center justify-end space-x-3 pt-6 border-t border-gray-200">
              <button
                type="button"
                @click="closeModal"
                class="inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-gray-500"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="saving"
                class="inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed bg-blue-500 text-white hover:bg-blue-600 focus:ring-blue-500"
              >
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 批量导入弹窗 -->
    <div v-if="showImportModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg w-full max-w-md">
        <div class="p-6">
          <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-semibold text-gray-900">批量导入学生</h3>
            <button
              @click="showImportModal = false"
              class="text-gray-400 hover:text-gray-600"
            >
              <i class="icon-[heroicons--x-mark] w-6 h-6"></i>
            </button>
          </div>
          
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">选择Excel文件</label>
              <input
                type="file"
                accept=".xlsx,.xls"
                @change="handleFileSelect"
                class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
              >
            </div>
            
            <div class="text-sm text-gray-600">
              <p class="mb-2">导入说明：</p>
              <ul class="list-disc list-inside space-y-1 text-xs">
                <li>支持.xlsx和.xls格式</li>
                <li>第一行为表头，包含：姓名、学号、性别、身份证号、手机号、专业</li>
                <li>最多支持1000条记录</li>
              </ul>
            </div>
            
            <div class="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200">
              <button
                @click="showImportModal = false"
                class="inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-gray-500"
              >
                取消
              </button>
              <button
                @click="importStudents"
                :disabled="!selectedFile || importing"
                class="inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed bg-blue-500 text-white hover:bg-blue-600 focus:ring-blue-500"
              >
                {{ importing ? '导入中...' : '开始导入' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAdminStore } from '../../stores/admin'
import { useAppStore } from '../../stores/app'
import { DataTable } from '../../components'

// 使用stores和路由
const adminStore = useAdminStore()
const appStore = useAppStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const importing = ref(false)
const searchQuery = ref('')
const selectedMajor = ref('')
const selectedStatus = ref('')
const selectedStudents = ref([])
const selectedFile = ref(null)

// 弹窗状态
const showAddModal = ref(false)
const showEditModal = ref(false)
const showImportModal = ref(false)

// 学生表单
const studentForm = reactive({
  id: null,
  name: '',
  studentId: '',
  sex: '0',
  idCard: '',
  contactPhone: '',
  majorId: '',
  className: '',
  paymentStatus: '0',
  status: '0',
  dormBuilding: '',
  roomNumber: ''
})

// 分页数据
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const tableColumns = [
  {
    key: 'avatar',
    title: '头像',
    slot: 'avatar',
    width: '80px'
  },
  {
    key: 'studentId',
    title: '学号',
    sortable: true,
    width: '120px'
  },
  {
    key: 'name',
    title: '姓名',
    sortable: true,
    width: '100px'
  },
  {
    key: 'sex',
    title: '性别',
    formatter: (value) => value === '0' ? '男' : '女',
    width: '60px'
  },
  {
    key: 'majorName',
    title: '专业',
    width: '120px'
  },
  {
    key: 'className',
    title: '班级',
    width: '100px'
  },
  {
    key: 'contactPhone',
    title: '联系电话',
    width: '120px'
  },
  {
    key: 'status',
    title: '报到状态',
    slot: 'registrationStatus',
    width: '100px'
  },
  {
    key: 'paymentStatus',
    title: '缴费状态',
    slot: 'paymentStatus',
    width: '100px'
  },
  {
    key: 'dormBuilding',
    title: '入住地点',
    width: '120px'
  },
  {
    key: 'roomNumber',
    title: '寝室号',
    width: '100px'
  },
  {
    key: 'actions',
    title: '操作',
    slot: 'actions',
    width: '100px',
    fixed: 'right'
  }
]

// 计算属性
const students = computed(() => adminStore.students)
const majors = computed(() => adminStore.majors)

const filteredStudents = computed(() => {
  let result = students.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(student => 
      student.name.toLowerCase().includes(query) ||
      student.studentId.toLowerCase().includes(query) ||
      (student.contactPhone && student.contactPhone.includes(query)) ||
      (student.idCard && student.idCard.includes(query))
    )
  }
  
  // 专业过滤
  if (selectedMajor.value) {
    result = result.filter(student => student.majorId === selectedMajor.value)
  }
  
  // 状态过滤
  if (selectedStatus.value) {
    result = result.filter(student => student.registrationStatus === selectedStatus.value)
  }
  
  return result
})

// 方法
const getRegistrationStatusText = (status) => {
  const statusMap = {
    '0': '未报到',
    '1': '已报到'
  }
  return statusMap[status] || '未知'
}

const getPaymentStatusText = (status) => {
  const statusMap = {
    '0': '未缴费',
    '1': '已缴费'
  }
  return statusMap[status] || '未知'
}

const handleSearch = async () => {
  pagination.value.current = 1
  await refreshData()
}

const handleFilter = async () => {
  pagination.value.current = 1
  await refreshData()
}

const handleSelectionChange = ({ selectedData }) => {
  selectedStudents.value = selectedData
}

const handlePageChange = async ({ current, pageSize }) => {
  pagination.value.current = current
  pagination.value.pageSize = pageSize
  await refreshData()
}

const editStudent = (student) => {
  Object.assign(studentForm, student)
  showEditModal.value = true
}

const deleteStudent = async (student) => {
  if (confirm(`确定要删除学生 ${student.name} 吗？`)) {
    try {
      await adminStore.deleteStudent(student.id)
      appStore.showSuccess('删除成功')
      await refreshData()
    } catch (error) {
      appStore.showError('删除失败')
    }
  }
}

const handleBatchDelete = async () => {
  if (confirm(`确定要删除选中的 ${selectedStudents.value.length} 个学生吗？`)) {
    try {
      const ids = selectedStudents.value.map(student => student.id)
      await adminStore.batchDeleteStudents(ids)
      appStore.showSuccess('批量删除成功')
      selectedStudents.value = []
      await refreshData()
    } catch (error) {
      appStore.showError('批量删除失败')
    }
  }
}

const saveStudent = async () => {
  saving.value = true
  try {
    if (showAddModal.value) {
      await adminStore.createStudent(studentForm)
      appStore.showSuccess('添加成功')
    } else {
      await adminStore.updateStudent(studentForm.id, studentForm)
      appStore.showSuccess('更新成功')
    }
    closeModal()
    await refreshData()
  } catch (error) {
    appStore.showError(showAddModal.value ? '添加失败' : '更新失败')
  } finally {
    saving.value = false
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  Object.assign(studentForm, {
    id: null,
    name: '',
    studentId: '',
    sex: '0',
    idCard: '',
    contactPhone: '',
    majorId: '',
    className: '',
    paymentStatus: '0',
    status: '0',
    dormBuilding: '',
    roomNumber: ''
  })
}

const handleFileSelect = (event) => {
  selectedFile.value = event.target.files[0]
}

const importStudents = async () => {
  if (!selectedFile.value) return
  
  importing.value = true
  try {
    await adminStore.importStudents(selectedFile.value)
    appStore.showSuccess('导入成功')
    showImportModal.value = false
    selectedFile.value = null
    await refreshData()
  } catch (error) {
    appStore.showError('导入失败')
  } finally {
    importing.value = false
  }
}

// 头像相关方法
const isValidPhotoUrl = (photo) => {
  if (!photo || typeof photo !== 'string') return false
  
  // 检查是否为有效的URL格式
  try {
    const url = new URL(photo)
    return url.protocol === 'http:' || url.protocol === 'https:'
  } catch {
    return false
  }
}

const handleImageError = (event) => {
  // 图片加载失败时隐藏图片，让默认样式显示
  event.target.style.display = 'none'
}

const exportStudents = async () => {
  try {
    await adminStore.exportStudents(filteredStudents.value)
    appStore.showSuccess('导出成功')
  } catch (error) {
    appStore.showError('导出失败')
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize
    }
    await adminStore.getStudents(params)
    await adminStore.getMajors()
  } catch (error) {
    appStore.showError('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(async () => {
  appStore.setPageTitle('学生管理')
  await refreshData()
})
</script>

<style scoped>
@reference "tailwindcss";

.admin-students {
  min-height: calc(100vh - 64px);
}
</style>